﻿using AntdUI;
using ImportPlcPointPosition.Controls.Base;
using ImportPlcPointPosition.Core;
using ImportPlcPointPosition.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZR.Model.Models.ProductionControl;

namespace ImportPlcPointPosition.Controls.Pages
{
    public partial class TechnicalFlowPage : BaseUserControl
    {
        #region Fields
        
        private BindingList<CksTechnicalFlowNodes> Source = new BindingList<CksTechnicalFlowNodes>();
        private BindingList<CksPlcActions> ActionsSource = new BindingList<CksPlcActions>();
        private BindingList<CksValidationField> ValidationFields = new BindingList<CksValidationField>();
        private CksTechnicalFlowNodes Context = null;

        #endregion

        /// <summary>
        /// 工艺路线
        /// </summary>
        public TechnicalFlowPage()
        {
            InitializeComponent();
            this.Load += TechniqueRoadPage_Load;
        }

        #region Methods

        private void InitData()
        {
            var db = SqlSugarHelper.MesDB;
            var lst = db.Queryable<CksVirtualTable>()
                   .OrderBy(a => a.Sequence)
                   .ToList();
            CellButtonHelper.Tables = lst;
            List<ISelectItem> items = new List<ISelectItem>();
            foreach (var t in lst)
            {
                items.Add(new AntdUI.SelectItem(t.TableName, t.Id));
            }
            CellButtonHelper.TableDropDownItems = items.ToArray();
        }

        private void InitTable()
        {
            table1.EditMode = TEditMode.Click;
            table1.Columns = new ColumnCollection();
            table1.Columns.Add(new Column("NodeId", "节点编号").SetAlign());
            table1.Columns.Add(new Column("Notes", "说明").SetAlign());
            // table1.Columns.Add(new Column("TableId", "表ID"));
            table1.Columns.Add(new Column("TableItem", "数据表").SetAlign()); // 采用下拉选择
            table1.Columns.Add(new ColumnCheck("AllowReprocess", "允许重复加工").SetAlign());
            table1.Columns.Add(new ColumnCheck("AllowOkReprocess", "允许OK件重复加工").SetAlign());
            table1.Columns.Add(new ColumnCheck("RequireOk", "结果是否必须OK").SetAlign());
            table1.Columns.Add(new Column("PreNodeId", "前置节点编号").SetAlign());
            table1.Columns.Add(new ColumnCheck("NeedPrevCheck", "是否验证前置节点").SetAlign());
            table1.Columns.Add(new ColumnCheck("Nullity", "禁用").SetAlign());
            table1.Bordered = true;
            table1.EnableHeaderResizing = false;
            table1.EmptyHeader = true;
            table1.Gap = 6;
            table1.VisibleHeader = true;

            table1.Binding(Source);
            table1.CellBeginEditInputStyle += (s, e) =>
            {
                e.Input.SelectAll();
            };
            table1.CellClick += Table1_CellClick;
        }

        private void Table1_CellClick(object sender, TableClickEventArgs e)
        {
            var config = e.Record as CksTechnicalFlowNodes;
            Context = config;
            if (e.Button == MouseButtons.Left)
            {
                LoadActionData(Context);
            }
        }

        private void InitActionTable()
        {
            tableAction.EditMode = TEditMode.Click;
            tableAction.Columns = new ColumnCollection();

            tableAction.Columns.Add(new ColumnCheck("IsCheck").SetAlign());
            //tableAction.Columns.Add(new Column("PlcId", "PlcId").SetAlign());
            tableAction.Columns.Add(new Column("PlcIdCellText", "PLC").SetAlign());
            tableAction.Columns.Add(new Column("ActionId", "动作编号").SetAlign());
            tableAction.Columns.Add(new Column("ActionKey", "动作Key").SetAlign());
            //tableAction.Columns.Add(new Column("ReadDB", "ReadDB").SetAlign());
            //tableAction.Columns.Add(new Column("WriteDB", "WriteDB").SetAlign()); 
            tableAction.Columns.Add(new Column("DBblockCellText", "ReadDB").SetAlign());
            tableAction.Columns.Add(new Column("DBblockCellText", "WriteDB").SetAlign());

            tableAction.Bordered = true;
            tableAction.EnableHeaderResizing = true;
            tableAction.EmptyHeader = true;
            tableAction.Gap = 6;
            tableAction.VisibleHeader = true;
            tableAction.CellBeginEditInputStyle += (s, e) =>
            {
                e.Input.SelectAll();
            };

        }

        private void InitValidationFieldTable()
        {
            tableValidationField.EditMode = TEditMode.Click;
            tableValidationField.Columns = new ColumnCollection();
            tableValidationField.Columns.Add(new ColumnCheck("IsCheck").SetAlign());
            tableValidationField.Columns.Add(new Column("Sequence", "验证顺序").SetAlign());
            tableValidationField.Columns.Add(new Column("Notes", "说明").SetAlign());
            tableValidationField.Columns.Add(new Column("DataId", "数据编号").SetAlign());
            tableValidationField.Columns.Add(new ColumnCheck("IsPrimary", "是否主码").SetAlign());
            //table2.Columns.Add(new ColumnCheck("IsResult", "是否结果"));

            tableValidationField.Bordered = true;
            tableValidationField.EnableHeaderResizing = true;
            tableValidationField.EmptyHeader = true;
            tableValidationField.Gap = 6;
            tableValidationField.VisibleHeader = true;
            tableValidationField.CellBeginEditInputStyle += (s, e) =>
            {
                e.Input.SelectAll();
            };
          

        }

        public bool HasDuplicateProperty<T, TProp>(List<T> list, Func<T, TProp> selector)
        {
            var set = new HashSet<TProp>();
            foreach (var item in list)
            {
                if (!set.Add(selector(item)))
                {
                    return true;
                }
            }
            return false;
        }

        private void ReflushData()
        {
            InitData();
            Source.Clear();

            var db = SqlSugarHelper.MesDB;
            var lst = db.Queryable<CksTechnicalFlowNodes>()
                   .OrderBy(a => a.NodeId)
                   .ToList();
            foreach (var item in lst)
            {
                Source.Add(item);
            }
            if (Source.Count > 0)
            {
                table1.SelectedIndex = 1;
                Context = Source[0];
                LoadActionData(Context);
            }
            else
            {
                table1.SelectedIndex = -1;
                Context = null;
                ActionsSource.Clear();
                ValidationFields.Clear();
            }
        }

        private void LoadActionData(CksTechnicalFlowNodes context)
        {
            if (context == null) {
                return;
            }

            ActionsSource.Clear();
            var db = SqlSugarHelper.MesDB;
            var lst = db.Queryable<CksPlcActions>().Where(a => a.ActionType == 2 && a.BusinessId == context.Id).OrderBy(a => a.Id).ToList();
            foreach (var item in lst)
            {
                ActionsSource.Add(item);
            }
            this.tableAction.Binding(ActionsSource);

            LoadValidationFields(context);
        }

        private void LoadValidationFields(CksTechnicalFlowNodes context)
        {
            if (context == null) {
                return;
            }

            ValidationFields.Clear();
            var db = SqlSugarHelper.MesDB;
            var lst = db.Queryable<CksValidationField>().Where(a =>  a.BusinessId == context.Id).OrderBy(a => a.Sequence).ToList();
            foreach (var item in lst)
            {
                ValidationFields.Add(item);
            }
            this.tableValidationField.Binding(ValidationFields);

        }

        #endregion

        #region Events

        private void TechniqueRoadPage_Load(object sender, EventArgs e) {
            InitData();
            InitTable();
            InitActionTable();
            InitValidationFieldTable();
            ReflushData();
        }

        private void btnImport_Click(object sender, EventArgs e) {

            if (CellButtonHelper.Tables.Count == 0) {
                MessageError("请先配置采集表");
                return;
            }
            var result = MessageBoxWarn("从虚拟表提取数据，是否继续？");
            if (result == DialogResult.OK) {
                InitData();
                foreach (var item in CellButtonHelper.Tables) {
                    var one = Source.ToList().Find(a => a.TableId == item.Id);
                    if (one == null)
                        Source.Add(new CksTechnicalFlowNodes() { TableId = item.Id, Notes = item.Notes });
                }
            }
        }

        private void btnLoadData_Click(object sender, EventArgs e) {
            ReflushData();
        }

        /// <summary>
        /// 添加新节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e) {
            Source.Add(new CksTechnicalFlowNodes() { });
        }

        private void btnDelete_Click(object sender, EventArgs e) {

            var result = MessageBoxWarn("确认要删除吗？");
            if (result != DialogResult.OK)
                return;
            if (table1.SelectedIndex < 0)
                return;
            var db = SqlSugarHelper.MesDB;
            var row = Source[table1.SelectedIndex - 1];

            //1.删除动作
            db.Deleteable<CksPlcActions>().Where(a => a.ActionType == 2 && a.BusinessId == row.Id).ExecuteCommand();
            //2.删除字段
            db.Deleteable<CksValidationField>().Where(a => a.BusinessId == row.Id).ExecuteCommand();
            //3.删除工艺
            db.Deleteable(row).ExecuteCommand();
            //Source.Remove(row);
            //刷新
            ReflushData();
        }

        private void btnSave_Click(object sender, EventArgs e) {
            if (HasDuplicateProperty(Source.ToList(), (a) => a.TableId)) {
                MessageError("表格配置重复！");
                return;
            }
            if (HasDuplicateProperty(Source.ToList(), (a) => a.NodeId)) {
                MessageError("节点编号不允许重复！");
                return;
            }
            var items = Source.ToList().OrderBy(a => a.NodeId).ToList();
            if (items.Any(o => string.IsNullOrEmpty(o.Notes))) {
                MessageError("说明字段不允许为空！");
                return;
            }
            var db = SqlSugarHelper.MesDB;
            foreach (var item in items) {

                if (item.Id == 0)
                    db.Insertable(item).ExecuteCommand();
                else
                    db.Updateable(item).ExecuteCommand();
            }
            MessageSuccess("保存成功！");
            ReflushData();
        }

        /// <summary>
        /// 添加动作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddAction_Click(object sender, EventArgs e)
        {
            var cksPlcActions = new CksPlcActions();
            if (ActionsSource.Count == 0) {
                cksPlcActions.ActionId = 101;
                cksPlcActions.ActionKey = "WorkRequest";
            }
            ActionsSource.Add(cksPlcActions);
        }

        private void btnSaveActions_Click(object sender, EventArgs e)
        {
            try {

                if (Context == null) return;
                var items = ActionsSource.ToList().OrderBy(a => a.ActionId).ToList();
                var db = SqlSugarHelper.MesDB;
                foreach (var item in items) {
                    item.BusinessId = Context.Id;
                    item.ActionType = 2;
                    item.Name = "工艺路线";
                    if (item.Id == 0)
                        db.Insertable(item).ExecuteCommand();
                    else
                        db.Updateable(item).ExecuteCommand();
                }
                LoadActionData(Context);
                MessageSuccess("保存成功！");

            } catch (Exception ex) {

                MessageBoxError(ex.Message);
                //throw;
            }

        }

        private void btnDelAction_Click(object sender, EventArgs e) 
        {
            var delList = ActionsSource.Where(o => o.IsCheck).ToList();
            if (delList.Count <= 0) {
                MessageError("请选择至少一条数据！");
                return;
            }
            var result = MessageBoxWarn("确认要删除所选择的数据吗？");
            if (result != DialogResult.OK)
                return;
            var db = SqlSugarHelper.MesDB;
            db.Deleteable(delList).ExecuteCommand();
            MessageSuccess("删除成功！");
            LoadActionData(Context);
        }

        /// <summary>
        /// 添加验证字段
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddValidationField_Click(object sender, EventArgs e)
        {
            int dataCode = 0;
            if (ActionsSource.FirstOrDefault() != null) {
                int count = ValidationFields.Count + 1;
                dataCode = ActionsSource.FirstOrDefault().ActionId * 100 + Convert.ToInt32(count.ToString("D2"));
            }

            if (ValidationFields.Count == 0) {

                ValidationFields.Add(new CksValidationField() { Sequence = 1, Notes = "工件主标识代码", DataId = dataCode, IsPrimary = true });

            } else {

                var sequence = ValidationFields.Max(o => o.Sequence) + 1;
                ValidationFields.Add(new CksValidationField() { Sequence = sequence, DataId = dataCode });

            }
               
        }

        private void btnSaveValidationField_Click(object sender, EventArgs e)
        {
            if (Context == null) return;
            var items = ValidationFields.ToList().OrderBy(a => a.Sequence).ToList();
            var db = SqlSugarHelper.MesDB;
            foreach (var item in items)
            {
                item.BusinessId = Context.Id;
                
              
                if (item.Id == 0)
                    db.Insertable(item).ExecuteCommand();
                else
                    db.Updateable(item).ExecuteCommand();
            }
            LoadValidationFields(Context);
            //LoadActionData(Context);
            MessageSuccess("保存成功！");
        }

        private void btnDeleteValidationField_Click(object sender, EventArgs e)
        {
            var delList = ValidationFields.Where(o => o.IsCheck).ToList();
            if (delList.Count <= 0) {
                MessageError("请选择至少一条数据！");
                return;
            }
            var result = MessageBoxWarn("确认要删除所选择的数据吗？");
            if (result != DialogResult.OK)
                return;
            var db = SqlSugarHelper.MesDB;
            db.Deleteable(delList).ExecuteCommand();
            MessageSuccess("删除成功！");
            LoadValidationFields(Context);
        }

        #endregion
    }
}
